package com.egrid.point.bury.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.poi.excel.WorkbookUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.egrid.point.bury.code.PageResponse;
import com.egrid.point.bury.code.Response;
import com.egrid.point.bury.code.SimpleResponse;
import com.egrid.point.bury.entity.BuryPoint;
import com.egrid.point.bury.entity.OrderInfo;
import com.egrid.point.bury.exception.BuryException;
import com.egrid.point.bury.service.BuryPointService;
import io.swagger.annotations.*;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * BuryPointController.java
 * Created at 2019-12-26
 * Created by Royal Warmer
 * Copyright (C) 2018 SAIC VOLKSWAGEN, All rights reserved.
 */
@Api(description = "埋点")
@RestController
@RequestMapping("/bury/point")
@CrossOrigin
public class BuryPointController {


    @Autowired
    private BuryPointService service;

    @ApiOperation("提交埋点记录")
    @PostMapping
    public Response save(@RequestBody List<BuryPoint> params) {
        String result = this.service.save(params);
        return SimpleResponse.success(result);
    }

    @ApiOperation("查询所有")
    @GetMapping
    public Response findAll() {
        List<BuryPoint> all = this.service.findAll();
        return SimpleResponse.success("查询成功", all);
    }

    @ApiOperation("分页查询")
    @GetMapping("/{page}/{size}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", paramType = "path"),
            @ApiImplicitParam(name = "size", paramType = "path")
    })
    public Response findByPages(@PathVariable int page, @PathVariable int size) {
        if (page <= 0 || size <= 0) {
            throw new BuryException("页码错误!");
        }
        Page<BuryPoint> pages = this.service.findByPages(page - 1, size);
        PageResponse success = PageResponse.success(pages.getContent(), pages.getTotalElements(), pages.getContent().size());
        return success;
    }

    @GetMapping("/test")
    public Response test() {
        this.service.autoinsert();
        return null;
    }

    @PostMapping("/upload")
    public void getOrderInfoList(MultipartFile file, int sheetIndex, int cellIndex, HttpServletResponse resp) throws Exception {

        String realPath = System.getProperty("java.io.tmpdir");
        File folder = new File(realPath);

        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString() +
                oldName.substring(oldName.lastIndexOf("."), oldName.length());
        File excel = new File(folder, newName);
        file.transferTo(excel);
        Workbook workbook = WorkbookFactory.create(excel);

        Sheet sheet = workbook.getSheetAt(sheetIndex);
        int lastRowNum = sheet.getLastRowNum();
        List<OrderInfo> orderInfos = new ArrayList<>(lastRowNum);
        for (int i = 1; i <= lastRowNum; i++) {
            Row row = sheet.getRow(i);
            if (row != null) {
                Cell cell = row.getCell(cellIndex);
                if (cell != null) {
                    String stringCellValue = cell.getStringCellValue();
                    if (!StringUtils.isEmpty(stringCellValue)) {
                        OrderInfo orderInfo = getOrderInfo(stringCellValue);
                        orderInfos.add(orderInfo);
                    }
                }
            }
        }
        FileUtil.del(excel);
        workbook.close();
        File csv = new File(folder, newName.concat(".csv"));
        StringBuffer sb = new StringBuffer();
        resp.setContentType("application/msexcel;charset=UTF-8");
        resp.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(csv.getName(), "UTF-8"));
        ServletOutputStream outputStream = resp.getOutputStream();
        for (OrderInfo info : orderInfos) {

            for (OrderInfo.OrderItem orderItem : info.getOrderItems()) {


                sb.append("\"").append(info.getOrderDate()).append("\",")
                        .append("\"").append(info.getOrderUrl()).append("\",")
                        .append("\"").append(info.getOrderId()).append("\",")
                        .append("\"").append(info.getPaymentType()).append("\",")
                        .append("\"").append(orderItem.getProductName()).append("\",")
                        .append("\"").append(orderItem.getDeliveryDate()).append("\",")
                        .append("\"").append(orderItem.getTrackingNumber()).append("\",")
                        .append("\"").append(orderItem.getTrackingType()).append("\",");

                sb.append(System.lineSeparator());
            }

        }
        outputStream.write(sb.toString().getBytes("UTF-8"));

        outputStream.flush();
        outputStream.close();

    }

    @PostMapping("/order")
    public OrderInfo getOrderInfo(String url) {
        OrderInfo orderInfo = new OrderInfo();
        try {

            Connection connect = Jsoup.connect(url);
            connect.header("User-Agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Mobile Safari/537.36");
            Document document = connect.get();

            String html = document.select("script#init_data").html();
            JSONObject jsonObject = JSONObject.parseObject(html);

            String paymentType = jsonObject.getJSONObject("orderDetail")
                    .getJSONObject("billingInfo")
                    .getJSONObject("d")
                    .getJSONObject("chinaPaymentImageData")
                    .getString("alt");

            JSONObject orderItems = jsonObject.getJSONObject("orderDetail")
                    .getJSONObject("orderItems");

            JSONObject orderHeader = jsonObject.getJSONObject("orderDetail")
                    .getJSONObject("orderHeader")
                    .getJSONObject("d");
            String orderPlacedDate = orderHeader.getString("orderPlacedDate");

            String orderNumber = orderHeader.getString("orderNumber");


            orderInfo.setOrderDate(orderPlacedDate);
            orderInfo.setOrderId(orderNumber);
            orderInfo.setPaymentType(paymentType);


            Set<String> orderItemsName = orderItems.keySet();
            List<OrderInfo.OrderItem> list = new ArrayList<>();
            orderItemsName.forEach(name -> {
                if (name.startsWith("orderItem-")) {
                    OrderInfo.OrderItem data = new OrderInfo.OrderItem();
                    JSONObject orderItem = orderItems.getJSONObject(name);
                    JSONObject item = orderItem.getJSONObject("orderItemDetails")
                            .getJSONObject("d");
                    String productName = item.getString("productName");

                    data.setProductName(productName);
                    String deliveryDate = item.getString("deliveryDate");
                    data.setDeliveryDate(deliveryDate);
                    JSONObject d = orderItem.getJSONObject("orderItemStatusTracker")
                            .getJSONObject("d");
                    if (d != null) {
                        JSONArray jsonArray = d.getJSONArray("trackingUrls");
                        if (jsonArray != null) {
                            Object trackingPath = jsonArray.get(0);

                            if (trackingPath != null) {
                                int indexOf = trackingPath.toString().lastIndexOf("/");
                                String trackingNumber = trackingPath.toString().substring(indexOf + 1);
                                data.setTrackingNumber(trackingNumber);
                            }
                        }

                    }

                    list.add(data);

                }

            });
            orderInfo.setOrderItems(list);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            orderInfo.setOrderUrl(url);
        }
        return orderInfo;
    }


}
